<?php

namespace App\Models;

use App\Events\UpdateMenuSession;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Validator;

class AdminPermission extends Model
{
    use DataTables;

    protected $table='admin_permissions';

    public $fillable = ['name','rule','description','pid','is_menu','icon','sort'];

    public function roles()
    {
        return $this->belongsToMany(AdminRole::class,'admin_permission_role','permission_id','role_id');
    }

    /**
     *  数据装载
     */
    public function loadSave($data, $update_id = 0)
    {
        //数据验证
        $validator = Validator::make($data, $this->rule(), $this->message());
        if($validator->fails()){
            return [
                'code' => 0,
                'status' => 'error',
                'msg' => $validator->errors()->first()
            ];
        }
        if($update_id){
            $obj = AdminPermission::find($update_id);
            $re = $obj->update($data);
        }else{
            $re = AdminPermission::create($data);
        }
        if($re){
            //更新权限缓存
            event(new UpdateMenuSession());

            return [
                'code' => 1,
                'status' => 'success',
                'msg' => '成功',
            ];
        }else{
            return [
                'code' => 0,
                'status' => 'error',
                'msg' => '失败',
            ];
        }

    }

    /**
     *  验证规则
     */
    protected function rule()
    {
        return [
            'name' => 'required',
        ];
    }

    /**
     *  验证消息
     */
    protected function message()
    {
        return [
            'name.required' => '必须填写'
        ];
    }

    /*
     *  权限换成多维数组形式
     */
    public function arrayAllPermission()
    {
        //目前只是二级菜单
        $all_first = AdminPermission::where('pid',0)->get()->toArray();
        $all_p = AdminPermission::all()->toArray();
        foreach ($all_first as $k_f => $v_f){
            foreach ($all_p as $k => $v){
                if($v['pid'] == $v_f['id']){
                    $all_first[$k_f]['child'][] = $v;
                }
            }
        }
        unset($all_p);
        return $all_first;
    }

}
